<template>
  <div class="group-list-container">
    <el-input v-model="searchText" placeholder="请输入分组名" clearable :prefix-icon="Search" class="group-search" />

    <el-button type="primary" :icon="Plus" class="add-button" @click="handleAddGroup">
      {{ props.questionType === '04' ? '添加技巧' : '添加分类' }}
    </el-button>

    <el-menu class="question-menu" :default-active="defaultActive" @select="onSelect">
      <template v-for="item in filteredGroups" :key="item.id">
        <MenuItem :item="item" :question-type="questionType" @add="handleAdd" @edit="handleEdit" @copy="handleCopy"
          @delete="handleDelete" />
      </template>
    </el-menu>
  </div>
</template>

<script setup lang="ts">
import { computed, PropType } from 'vue'
import MenuItem from './MenuItem.vue'
import { Plus, Search } from '@element-plus/icons-vue'

const searchText = ref('')

interface TreeNode {
  id: string | number
  name: string
  img?: string
  questionCount?: number
  children?: TreeNode[]
  [key: string]: any
}

const props = defineProps({
  treeData: {
    type: Array as PropType<TreeNode[]>,
    default: () => []
  },
  questionType: {
    type: String
  },
  defaultActive: {
    type: String
  }
})

const emit = defineEmits(['select', 'add', 'edit', 'delete', 'addParent', 'copy', 'copyChild'])

const filteredGroups = computed(() => {
  if (!searchText.value) return props.treeData
  return props.treeData.filter((group) => group.name.includes(searchText.value))
})

function findNode(id: string, nodes: TreeNode[]): TreeNode | null {
  for (const n of nodes) {
    if (String(n.id) === id) return n
    if (n.children?.length) {
      const hit = findNode(id, n.children)
      if (hit) return hit
    }
  }
  return null
}

function handleAddGroup() {
  emit('addParent')
}

function onSelect(index: string) {
  const node = findNode(index, props.treeData)
  emit('select', node)
}

function handleAdd(item: TreeNode) {
  emit('add', item)
}

function handleEdit(item: TreeNode) {
  console.log(item, 'item===');

  emit('edit', item)
}

function handleDelete(item: TreeNode) {
  emit('delete', item)
}
function handleCopy(item: TreeNode) {
  emit('copy', item)
}
</script>

<style scoped>
.question-menu {
  border-right: none;

  :deep(.el-sub-menu__title) {
    padding-right: 0;
  }

  :deep(.el-sub-menu__icon-arrow) {
    right: 268px;
  }
}

.group-list-container {
  width: 300px;
  padding: 12px;
  border-right: 1px solid #eee;
  background: #fff;
  box-sizing: border-box;
}

.group-search {
  width: 100%;
  margin-bottom: 10px;
}

.add-button {
  width: 100%;
  margin-bottom: 16px;
}
</style>
